#include "CommandArgs.h"
#include "Log.h"

#include <cstdlib>

CmdLineArgs::CmdLineArgs() : node_id(-1)
{
	initializeToDefaults();
}

CmdLineArgs::CmdLineArgs(int argc, char **argv) : node_id(-1)
{
	initializeToDefaults();
	parse_args(argc, argv);
}

void CmdLineArgs::initializeToDefaults()
{
	node_id = 0;
}

// Parses command line arguments
void CmdLineArgs::parse_args(int argc, char **argv)
{
	int c, old_optind;
	old_optind = optind;
	
	// 3rd argument to getopt is colon delimited list of allowed arguments (MUST END WITH A COLON!)
	while ((c = getopt(argc, argv, "i:")) != -1)
	{
		switch (c) {
		case 'i':
			parse_long(optarg, &node_id, argv[0], "node_id");
			break;
		default:
			lout << "WARNING: CommandArgs - " << argv[0] << ": unknown argument, continuing..." << endl;
		}
	}
	
	optind = old_optind;	// Reset optind in case the caller wants to getopt some more
}

void CmdLineArgs::parse_long(const char* arg, unsigned long* value, const char*, const char*)
{
	char* endptr;
 	*value = strtoul(arg, &endptr, 0);
	
  	if (*endptr != '\0' && !isspace(*endptr)) {
		lout << "WARNING: CommandArgs - Error parsing command line arguments, continuing..." << endl;
	}
}

